import random

from captcha.image import ImageCaptcha
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView
from venvs.models import User
import re
import redis
class CheckUsername(APIView):
    def get(self, request, username):
        rule = r'[a-zA-Z][a-zA-z0-9]{5,15}$'

        match_rs = re.findall(rule, username)
        if not match_rs:
            return Response({
                "code": 400,
                "msg": "用户名规则错误"
            })
        # 验证用户是否存在
        user_count = User.objects.filter(username=username).count()
        if not user_count:
            return Response({
                "code": 200,
                "msg": "用户已存在"
            })
        else:
            return Response({
                "code": 400,
                "msg": "用户名已存在"
            })
class CheckMoblie(APIView):
    def get(self, request, mobile):
        rule = r'1[3-9][0-9]{9}$'
        match_rs = re.findall(rule, mobile)
        if not match_rs:  # 判断是否符合规则
            return Response({  # 返回错误码和错误信息
            "code": 400,
            "msg": "手机号格式错误",
        })
        mobile_count = User.objects.filter(mobile=mobile).count
        if not mobile_count:
            return Response({
                "code": 400,
                "msg": "手机号已存在",
            })
        else:
            return Response({
                "code": 200,
                "msg": mobile,
            })

# 验证码生成
class ImageCode(APIView):
    def get(self, request, uuid):
        # 生成4位随机字符
        from captcha.image import ImageCaptcha
        random_num = random.randint(1000, 9999)
        random_str = str(random_num)

        # 生成验证码
        img = ImageCaptcha()
        img_byte = img.generate(random_str)
        # 把验证码存到redis数据库中
        r = redis.Redis(host="127.0.0.1")
        key = "code:" + uuid  # 设置数据库的key
        r.set(key, random_str, ex=300)
        return HttpResponse(img_byte,content_type='img_ping,D91B6C5C-CA3E-D0AA-4E90-921E0E376475')
class CheckImageCode(APIView):
    def get(self, request):
        uuid = request.query_params["imageCodeID"]
        code = request.query_params["imageCode"]
        # 去数据库查验
        r = redis.Redis(host="127.0.0.1")
        key = "code:" + uuid

        system_code = r.get(key)
        system_code = str(system_code, encoding="utf-8")
        if system_code.upper() != code.upper():
            return Response({
                "code": 400,
                "msg": "验证码错误",
            })
        return Response({
            "code": 200,
            "msg": "验证码通过",
        })

class Register(APIView):
    def post(self, request):
        # 前端传入 userName, pwd, mobile, agree
        username = request.data.get("userName")
        password = request.data.get("pwd")
        mobile = request.data.get("mobile")
        agree = request.data.get("agree")
        #验证参数
        if not all([username, password, mobile]):
            return Response({"code":204, "msg":"注册信息不完整！"})
        if not agree:
            return Response({"code":204, 'msg':"未同意用户使用协议"})

        # 存入数据库
        User.objects.create_user(username=username, password=password, mobile=mobile)

        # 返回响应
        return Response({"code":200, "msg":"注册成功！"})
